import Axios from "axios"
import { toast } from 'react-toastify'
import { getToken } from "./tools"

Axios.defaults.headers.common['Content-Type'] = 'application/json'

const baseUrl = 'http://121.36.28.99:8018/api/'

export function get(url, params) {
    const token = getToken()
    Axios.defaults.headers.common['api-access-token'] = token

    let httpUrl = baseUrl + url
    return new Promise((resolve, reject) => {
        Axios.get(httpUrl, { params }).then(res => {
            if (res.status === 200) {
                if (res.data.isSuccess) {
                    resolve(res.data)
                } else {
                    if (!res.data.hasRight && !res.data.isSuccess) {
                        toast.error(res.data.errorMessage || '请求异常，请联系管理员！')
                        localStorage.clear()
                        window.router.push('/login')
                    }
                }
            }
        }).catch(err => {
            toast.error('请求异常，请联系管理员！')
            reject(err)
        })
    })
}

export function post(url, params) {
    const token = getToken()
    Axios.defaults.headers.common['api-access-token'] = token

    let httpUrl = baseUrl + url
    return new Promise((resolve, reject) => {
        Axios.post(httpUrl, params).then(res => {
            if (res.data.isSuccess) {
                resolve(res.data)
            } else {
                toast.error(res.data.errorMessage || '请求异常，请联系管理员！')
            }
        }).catch(err => {
            toast.error('请求异常，请联系管理员！')
            reject(err)
        })
    })
}

